package com.ljy.system.marvel_sys.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.FileInputStream;

/**
 * 〈功能简述〉<br>
 * 七牛云文件上传工具类
 *
 * @author LiJunYi
 * @create 2019/7/19
 * @since 1.0.0
 */
public class QiniuCloundUtil {
    /**
     * 设置七牛云账号的AK和SK
     */
    private static final String ACCESS_KEY = "-neuzXu06QN-76Rp2l32IGGZ7cKGYKKt70IlmkCz";
    private static final String SECRET_KEY = "civebPT7h08ASS66SIGTzJzHdH-LvCXOSXKT109a";
    /**
     * 要上传的空间bucket
     */
    private static final String BUCKET = "marvel_static";
    /**
     * 外链地址
     */
    private static final String DOMAIN = "img.ljysys.work/";

    /**
     * @param file 文件对象
     * @param key  上传文件名
     * @return: String 外链文件地址
     * @since: 1.0.0
     * @Author:Administrator
     * @Date: 2019/7/19 17:14
     */
    public static String uploadImg(FileInputStream file, String key) {
        //文件的外链地址
        StringBuffer fileUrl = new StringBuffer(DOMAIN);
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //秘钥鉴权
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        //简单上传，使用默认策略，只需要设置上传的空间名就可以了
        String upToken = auth.uploadToken(BUCKET);
        Response res = null;
        try {
            //调用上传方法
            res = uploadManager.put(file, key, upToken,null,null);
            // 解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            fileUrl.append(putRet.key);
            // 返回外链文件地址
            return fileUrl.toString();
        } catch (QiniuException e) {
            e.printStackTrace();
            Response r = e.response;
            System.err.println(r.toString());
            return "upload_error";
        }
    }
}
